package com.linzm.leetcode.primary.exercises3_20230122;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author zimingl
 * @Date 2023/1/24 12:42
 * @Description: 转置矩阵
 */
public class Demo11_867 {
    /**
     * 给你一个二维整数数组 matrix， 返回 matrix 的 转置矩阵 。
     * 矩阵的 转置 是指将矩阵的主对角线翻转，交换矩阵的行索引与列索引。
     */
    public static void main(String[] args) {
        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        Demo11_867 demo11_867 = new Demo11_867();
        int[][] transpose = demo11_867.transpose(matrix);
        List<Integer> list = getList(transpose);
        String[] strings = list.stream().map(String::valueOf).toArray(String[]::new);
        System.out.println(String.join(" ", strings));
    }

    private static List<Integer> getList(int[][] transpose) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < transpose.length; i++) {
            for (int j = 0; j < transpose[i].length; j++) {
                list.add(transpose[i][j]);
            }
        }
        return list;
    }
    public int[][] transpose(int[][] matrix) {
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                List<Integer> orDefault = map.getOrDefault(j, new ArrayList<>());
                orDefault.add(matrix[i][j]);
                map.put(j, orDefault);
            }
        }
        int[][] res = new int[matrix.length][matrix[0].length];
        for (int i = 0; i < res.length; i++) {
            List<Integer> list = map.get(i);
            for (int j = 0; j < res[i].length; j++) {
                res[i][j] = list.get(j);
            }
        }
        return res;
    }

    public int[][] transpose2(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        int[][] transposed = new int[n][m];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                transposed[j][i] = matrix[i][j];
            }
        }
        return transposed;
    }
}
